package c2c

import (
	"gim-server/apis/ws"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type MarkC2cMsgReadArgs struct {
	FromUID string `json:"from_uid"`
}

func markC2cMsgRead(ctx *gin.Context) {
	var (
		err  error
		args = new(MarkC2cMsgReadArgs)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	err = db.Transaction(func(tx *gorm.DB) error {
		if args.FromUID != "" {
			if err = tx.Model(new(model.TbC2cMsgRecord)).Where("from_uid = ? and to_uid = ?", args.FromUID, ctx.GetString(consts.UID)).UpdateColumn("readed", true).Error; err != nil {
				return err
			}
			if err := tx.Model(new(model.TbConversation)).Where("from_uid = ? and to_uid = ?", ctx.GetString(consts.UID), args.FromUID).UpdateColumn("unread_count", 0).Error; err != nil {
				return err
			}
		} else {
			if err = tx.Model(new(model.TbC2cMsgRecord)).Where("to_uid = ?", ctx.GetString(consts.UID)).UpdateColumn("readed", true).Error; err != nil {
				return err
			}
			if err := tx.Model(new(model.TbConversation)).Where("from_uid = ?", ctx.GetString(consts.UID)).UpdateColumn("unread_count", 0).Error; err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiDbErr,
			Err:  err,
		})
		return
	}
	time.AfterFunc(time.Second, func() {
		if args.FromUID != "" {
			ws.MarkC2cMsgRead(ctx.GetString(consts.UID), args.FromUID)
		}
	})
	utils.SUC(ctx, true)
}
